<template>
  <div class="app-container" style="padding: 10px;">
    <el-card>
      <div class="search-div">
        <el-form label-width="70px" size="small">
          <el-row>
            <el-col :span="8">
              <el-form-item label="账号名称">
                <el-input style="width: 95%" v-model="params.accountNumber" placeholder="用户"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="类型">
                <el-select v-model="params.isUserType" placeholder="请选择类型">
                  <el-option v-for="item in userTypeOPtion" :key="item.id" :label="item.name"
                    :value="item.id"></el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-search" size="small" @click="fetchData()"
                  style="margin: 0 10px;">搜索</el-button>
                <el-button size="small" @click="resetData" style="margin: 0 10px;">重置</el-button>
                <el-button type="success" size="small" @click="add">添加管理员</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>



      <!-- 列表 -->
      <el-table v-loading="listLoading" :data="list" stripe border style="width: 100%;margin-top: 10px;">

        <el-table-column label="序号" width="70" align="center">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>

        <el-table-column prop="accountNumber" label="用户名" width="180" align="center" />
        <el-table-column prop="userName" label="姓名" width="100" align="center" />
        <el-table-column prop="isUserType" label="用户类型" width="180" align="center" />
        <el-table-column label="头像" align="center">
          <template #default="{row,$index}">
            <el-image style="width: 100px; height: 100px" :src="row.headUrl" :preview-src-list="[row.headUrl]" />
          </template>
        </el-table-column>
        <!-- <el-table-column prop="name" label="姓名" width="110" /> -->
        <el-table-column label="状态" width="80" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" active-color="#ff4949" inactive-color="#13ce66" :active-value="0"
              :inactive-value="1" @change="switchStatus(scope.row)">
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" width="200" align="center">
          <template slot-scope="scope">{{ scope.row.createTime | formatCreateTimes }}</template>
        </el-table-column>

        <el-table-column label="操作" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="warning" icon="el-icon-baseball" size="mini" @click="showAssignRole(scope.row)"
              title="分配角色" />
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(scope.row)" title="修改" />
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeDataById(scope.row.id)"
              title="删除" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination :current-page="params.pageNum" :total="total" :page-size="params.pageSize"
        style="float: right; margin-top: 10px;" background layout="total, prev, pager, next, jumper"
        @current-change="fetchData" />
    </el-card>
    <el-dialog title="添加/修改" :visible.sync="dialogVisible" width="40%">
      <el-form ref="dataForm" :model="sysUser" label-width="100px" size="small" style="padding-right: 40px;">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="sysUser.accountNumber" />
        </el-form-item>
        <!-- v-if="!sysUser.id"  -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="sysUser.password" type="password" />
        </el-form-item>
        <el-form-item label="头像" prop="password">
          <el-upload class="upload-demo" :action="uploadUrl" name="file" :limit="1" :on-success="handleSuccess"
            :on-remove="handleRemove" :file-list="fileList" list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small" icon="el-icon-refresh-right">取 消</el-button>
        <el-button type="primary" icon="el-icon-check" @click="saveOrUpdate()" size="small">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog title="分配角色" :visible.sync="dialogRoleVisible">
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input disabled :value="sysUser.accountNumber"></el-input>
        </el-form-item>

        <el-form-item label="角色列表">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
            @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="userRoleIds" @change="handleCheckedChange">
            <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">{{role.roleName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="assignRole" size="small">保存</el-button>
        <el-button @click="dialogRoleVisible = false" size="small">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    formatDate
  } from '../../../utils/date.js'

  const defaultForm = {
    id: '',
    username: '',
    password: '',
    name: '',
    phone: '',
    status: 1
  }
  export default {
    data() {
      return {
        listLoading: true, // 数据是否正在加载
        list: null, // banner列表
        total: 0, // 数据库中的总记录数
        params: {
          pageNum: 1,
          pageSize: 10
        },
        createTimes: [],
        dialogVisible: false,
        sysUser: defaultForm,
        saveBtnDisabled: false,
        fileList: [],
        userTypeOPtion: [{
          id: 0,
          name: "管理员"
        }, {
          id: 1,
          name: '教师'
        },
        {
          id: 2,
          name: "学生"
        }
        ],
        dialogRoleVisible: false,
        allRoles: [], // 所有角色列表
        userRoleIds: [], // 用户的角色ID的列表
        isIndeterminate: false, // 是否是不确定的
        checkAll: false // 是否全选
      }
    },
    filters: {
      formatCreateTimes(time) {
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd  hh:mm:ss')
      }
    },
    // 生命周期函数：内存准备完毕，页面尚未渲染
    created() {
      this.fetchData()
    },

    // 生命周期函数：内存准备完毕，页面渲染成功
    mounted() {
    },
    computed: {
      uploadUrl() {
        return process.env.VUE_APP_BASE_API + "/common/upload/file"
      }
    },
    methods: {
      // 加载banner列表数据
      fetchData(page = 1) {
        this.$api.user.getUserList(this.params).then(
          response => {
            //this.list = response.data.list
            this.list = response.data
            this.total = response.pageParams.total
            // 数据加载并绑定成功
            this.listLoading = false
          }
        )
      },

      // 重置查询表单
      resetData() {
        console.log('重置查询表单')
        this.createTimes = []
        this.params = {}
        this.params.pageNum = 1
        this.params.pageSize = 10
        this.fetchData()
      },

      // 根据id删除数据
      removeDataById(id) {
        // debugger
        this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.user.delUser(id).then((response) => {
            this.fetchData()
            this.$message.success(response.message || '删除成功')
          })
        })
      },

      //弹出添加表单
      add() {
        this.dialogVisible = true
        this.sysUser = {}
        this.fileList = []
      },
      //编辑
      edit(row) {
        this.fileList = []
        this.dialogVisible = true
        this.sysUser = row
        this.fileList.push({ name: "", url: row.headUrl })
      },
      //添加或更新
      saveOrUpdate() {
        if (!this.sysUser.id) {
          this.save()
        } else {
          this.update()
        }
      },

      //添加
      save() {
        if (this.sysUser.password == undefined || this.sysUser.password == "") {
          this.$message.warning("请填写密码~")
          return
        }
        if (this.fileList.length != 0) {
          this.sysUser.headUrl = this.fileList[0].url
        }
        console.log(this.sysUser);
        this.$api.user.addAdminUser(this.sysUser).then(res => {
          if (res.code == 200) {
            this.$message.success("添加成功~")
            this.fetchData()
            this.dialogVisible = false
          }
        })
      },

      //更新
      update() {
        console.log(this.sysUser);
        let url = "";
        if (this.fileList.length != 0) {
          url = this.fileList[0].url
        } else {
          url = this.sysUser.headUrl
        }
        let params = {
          id: this.sysUser.id,
          accountNumber: this.sysUser.accountNumber,
          password: this.sysUser.password || "",
          headUrl: url,
          userDetailId: 0
        }
        this.$api.user.updateUser(params).then(res => {
          if (res.code == 200) {
            this.$message.success("修改成功~")
            this.dialogVisible = false
            this.fetchData()
          }
        })

      },
      switchStatus(row) {
        this.$api.user.updateStatus(row.id, row.status).then(res => {
          if (res.code == 200) {
            this.$message.success("设置成功~")
            this.fetchData()
          }
        })

      },
      handleSuccess(response, file, fileList) {
        this.fileList.push({ name: file.name, url: response.data })
      },
      handleRemove(file, fileList) {
        this.fileList = []
      },
      //展示分配角色
      showAssignRole(row) {
        this.sysUser = row
        this.dialogRoleVisible = true
        this.$api.role.getRolesByUserId(row.id).then(response => {
          this.allRoles = response.data.allRoles
          this.userRoleIds = response.data.userRoleIds
          this.checkAll = this.userRoleIds.length === this.allRoles.length
          this.isIndeterminate = this.userRoleIds.length > 0 && this.userRoleIds.length < this.allRoles.length
        })
      },

      /*
      全选勾选状态发生改变的监听
      */
      handleCheckAllChange(value) {// value 当前勾选状态true/false
        // 如果当前全选, userRoleIds就是所有角色id的数组, 否则是空数组
        this.userRoleIds = value ? this.allRoles.map(item => item.id) : []
        // 如果当前不是全选也不全不选时, 指定为false
        this.isIndeterminate = false
      },

      /*
      角色列表选中项发生改变的监听
      */
      handleCheckedChange(value) {
        const { userRoleIds, allRoles } = this
        this.checkAll = userRoleIds.length === allRoles.length && allRoles.length > 0
        this.isIndeterminate = userRoleIds.length > 0 && userRoleIds.length < allRoles.length
      },

      //分配角色
      assignRole() {
        let assginRoleVo = {
          userId: this.sysUser.id,
          roleIdList: this.userRoleIds
        }
        this.$api.role.assignRoles(assginRoleVo).then(response => {
          this.$message.success(response.message || '分配角色成功')
          this.dialogRoleVisible = false
          this.fetchData()
        })
      },
    }
  }
</script>